package com.golxen.framework.common.server.game.cmd.sync;


import com.golxen.framework.CrossProtocol;
import com.golxen.framework.GameProtocol;
import com.golxen.framework.PBPacket.PBPacket;
import com.golxen.framework.PBPacket.PBPacketUtils;
import com.golxen.framework.common.BuiltinPlugin;
import com.golxen.framework.common.server.game.cmd.AbstractServerCommand;
import com.golxen.framework.common.server.game.cmd.Cmd;
import com.golxen.framework.netty.session.game.GameServerLinkedSet;
import com.golxen.framework.user.player.GamePlayerMgr;
import com.golxen.framework.common.server.game.sync.message.IGameServiceCommand;
import com.golxen.framework.common.server.game.sync.message.SyncResponse;
import com.golxen.framework.common.server.game.sync.message.SyncServiceMgr;
import com.golxen.protojava.SyncMessage;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.Message;

@Cmd(code = GameProtocol.S_GAME_SERVICE_HANDLER, desc = "非阻塞同步消息到游戏服处理")
public class SyncGameMessageHandlerCmd extends AbstractServerCommand {

	private SyncMessage.Request request;


    @Override
    public Message parseData(PBPacket packet) throws Exception {
        request = SyncMessage.Request.parseFrom(packet.getBytes());
        return request;
    }

    @Override
    public void execute(PBPacket packet) throws Exception {
        IGameServiceCommand iGameServiceCommand = SyncServiceMgr.getSyncMessageService().getCommand(this.request.getCmdCode());
        if (iGameServiceCommand != null) {
            try {
                SyncMessage.Response.Builder builder = SyncMessage.Response.newBuilder();
                SyncResponse syncResponse = iGameServiceCommand.execute(this.request);
                builder.setErrorCode(syncResponse.getErrorCode());
                builder.setSequenceId(request.getSequenceId());
                builder.setForwardServerId(this.request.getRawServerId());
                long serverId = BuiltinPlugin.getServerId();
                builder.setActivityId(this.request.getActivityId());
                builder.setRawServerId(serverId);
                builder.setCmdCode(GameProtocol.S_CROSS_SERVICE_MESSAGE_RESP);
                if (syncResponse.getResponseBuilder() != null) {
                    builder.setDataBytes(syncResponse.getResponseBuilder().build().toByteString());
                }
                int code = CrossProtocol.C_SERVICE_BACK_MESSAGE;
                if (this.request.getActivityId() > 0) {
                    code = CrossProtocol.C_CROSS_ACTIVITY_RESP_HANDLER;
                }
                PBPacket message = PBPacketUtils.buildMessage(code, builder);
                GameServerLinkedSet.send(this.request.getSenderId(), message);
            } catch (InvalidProtocolBufferException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void sendData(PBPacket packet) throws Exception {

    }

}
